//
//  CZOauthViewController.swift
//  1215微博终极项目
//
//  Created by chok崋 on 15/12/19.
//  Copyright © 2015年 周卓华. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZOauthViewController: UIViewController,UIWebViewDelegate {

    //从webView开始加载的时候(代理方法)
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载信息", maskType: SVProgressHUDMaskType.Black)
    }
    
    //加载完成webView的时候自动关闭显示框
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //使用这个加载不同添加约束,把view自动替换成webView
    override func loadView() {
        view = webView
        //给webView设置代理
        webView.delegate = self
    }
    
    //拦截回调网址,返回TRUE是去加载，false是不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获得加载的网址
        let url = request.URL!.absoluteString
        //判断网址的前缀是否是百度网址,不是的去加载，是的跳过if，继续运行
        if !url.hasPrefix(CZNetWorktool.CZNetWorkInstance.redirect_uri)
        {
           return true
        }
        
        // 是授权回调地址,判断是取消还是授权
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击授权:会以code=开头 http://www.baidu.com/?code=a61c2d7ec7b8c4c9c1962bf4354354c5
        // 获取url中?后面的内容: URL.query就是问号后面的东西
        
        if let query = request.URL?.query
        {
             let codeString = "code="
            //判断是否授权
            if query.hasPrefix(codeString)
            {
               //授权成功，截取代码
                //强制转换NSString
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
                print("code:\(code)")
                
                //调用当前类的加载accesstoken方法
                loadAccessToken(code)
            }else
            {
               self.close()
            }
        }
        
        return false
    }
    
    //返回单例的post请求accesstoken的方法
    func loadAccessToken(code:String)
    {
        CZNetWorktool.CZNetWorkInstance.loadAcessToken(code) { (result, error) -> () in
            //判断网络请求是否有错误
            if error != nil
            {
               SVProgressHUD.showInfoWithStatus("你的网络不给力")
                //自动关闭页面
                self.close()
            }
            //取到accesstoken
            print("result:\(result)")
            
            //获得返回的模型
            let userAccount = CZUserAccount(dict: result!)
           // NSHomeDirectory()
            //将accessToken进行归档
            userAccount.saveUserAccount()
            print("userAccount:\(userAccount)")
            
            //切换到欢迎界面
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
            
            //关闭授权界面
            self.close()
         }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //通过单例获得已经拼接好得URL
        let url =  CZNetWorktool.CZNetWorkInstance.oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        //设置左边的按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFull")
        
        //设置右边的按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.title = "登录"
    }
    
    func autoFull()
    {
        let js = "document.getElementById('userId').value='15992184734'; document.getElementById('passwd').value='15992184734';"
        
        //让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func close ()
    {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
   
 //mark --懒加载
    lazy var webView = UIWebView()
}
